/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include "utils_noncopyable.h"
#include <functional>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <future>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>

namespace El {
namespace Utils {

class TaskScheduler {
    DISALLOW_COPY_AND_MOVE(TaskScheduler);

public:
    using TaskFunction = std::function<void()>;

    static TaskScheduler &GetInstance();

    std::future<void> PostTask(const std::string &taskName, const TaskFunction &taskFunc);
    void SetThreadPoolSize(size_t size);

private:
    TaskScheduler();
    ~TaskScheduler();

    struct TaskItem {
        std::string name;
        TaskFunction func;
    };

    std::vector<std::thread> workers_;
    std::unordered_map<std::string, std::queue<TaskItem>> taskQueues_;
    std::unordered_set<std::string> processingTasks_;
    std::mutex queueMutex_;
    std::condition_variable condition_;
    bool stop_ = false;

    void initializeThreadPool(size_t size);
    void workerThread();
};

} // namespace Utils
} // namespace El